package com.yn.xgame.access;

import com.yn.xgame.IFuncServerLike;
import com.yn.xgame.IMessage;
import com.yn.xgame.LoadInfoManager;
import com.yn.xgame.ThreadServer;
import com.yn.xgame.message.C2APbMessage;
import com.yn.xgame.pb.ClientAccessProto;
import com.yn.xgame.pb.MessageIdProto;
import com.yn.xgame.po.LoadInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * AccessServer
 * Created by wangboo on 2017/7/12.
 */
public class AccessServer extends ThreadServer implements IFuncServerLike {

    private static final Logger logger = LoggerFactory.getLogger(AccessServer.class);
    LoadInfoManager loadInfoManager;
    private int state = 0; // 状态 0 正常工作，1维护中，2已停服，

    public AccessServer() {
        super("AccessServer");
        loadInfoManager = new LoadInfoManager();
    }

    @Override
    public boolean handleMessage(IMessage message) {
        if(super.handleMessage(message)) return true;
        if (message instanceof C2APbMessage) {
            return handleC2AMessage((C2APbMessage)message);
        }
        return false;
    }

    private boolean handleC2AMessage(C2APbMessage msg) {
        switch (msg.getMsgId()) {
            case C2A_GateList:
                handleGateList(msg);
                return true;
            default:
                logger.warn("recv unknown c2aMessage: {}", msg.getProto());
                return false;
        }
    }

    private void handleGateList(C2APbMessage msg) {
        ClientAccessProto.C2A_GateListResp.Builder bu = ClientAccessProto.C2A_GateListResp.newBuilder();
        bu.setState(state);
        if (state == 0) {
            loadInfoManager.getWorkingList().forEach(s -> bu.addInfo(
                    ClientAccessProto.C2A_GateListResp.GateInfo.newBuilder()
                        .setIp(s.ip)
                        .setPort(s.port)
                    )
            );
        }

        ClientAccessProto.A2CMessage resp = ClientAccessProto.A2CMessage.newBuilder()
                .setMsgid(MessageIdProto.MessageId.A2C_GateListResp)
                .setGatelistresp(bu)
                .build();
        msg.sendAndClose(resp);
    }

    // func callbacks
    public void addOrUpdate(LoadInfo info) {
        loadInfoManager.addOrUpdate(info);
    }

    public void remove(int id) {
        loadInfoManager.remove(id);
    }

}
